package com.hengxinguotong.zhihuichengjian.ui.building;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.NoticeListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.MenuBean;
import com.hengxinguotong.zhihuichengjian.bean.MenuListRes;
import com.hengxinguotong.zhihuichengjian.bean.Notice;
import com.hengxinguotong.zhihuichengjian.bean.NoticeListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/1/10
 */

public class NoticeListActivity extends BaseActivity implements View.OnClickListener, NoticeListAdapter.OnClickListener, TextWatcher {
    private static final String TAG = "NoticeListActivity";
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.add)
    HXTextView add;
    @BindView(R.id.title_et)
    HXEditTextView titleEt;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;

    private PullableRecyclerView dataRv;
    private List<Notice> noticeList;
    private NoticeListAdapter adapter;
    private List<MenuBean> menuList;//

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.UPDATE:
                    List<Notice> datas = (List<Notice>) msg.obj;
                    process(datas);
                    break;
            }
        }
    };
    private int page = 1;
    private boolean fromEnterprise = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice_list);
        ButterKnife.bind(this);
        fromEnterprise = getIntent().getBooleanExtra("fromEnterprise", false);
        initView();
        initData();
    }

    private void initView() {
        String title = getIntent().getStringExtra("title");
        titleTv.setText(title);

        String authority = SPUtil.getString(this, "authority");
        if(!Utils.isEmpty(authority)){
            try{
                MenuListRes menuListRes = new Gson().fromJson(authority, MenuListRes.class);
                menuList = menuListRes.getValue();
            }catch (Exception e){
                Log.e(TAG, e.getMessage().toString());
            }
        }
        if(menuList == null){
            menuList = new ArrayList<>();
        }
        add.setVisibility(View.GONE);
        for (MenuBean menu:menuList){
            if(menu.getId() == 1500){
                for(MenuBean sMenu:menu.getData()){
                    if(sMenu.getId() == 1530){
                        if(sMenu.getAuth().getAdd() == 1){
                            add.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        }

        titleEt.addTextChangedListener(this);

        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        noticeList = new ArrayList<>();
        adapter = new NoticeListAdapter(this, noticeList);
        dataRv.setAdapter(adapter);
        adapter.setOnClickListener(this);
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        dataRv.setItemAnimator(new DefaultItemAnimator());
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            page = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            page = noticeList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getNoticeList("加载中…");
            }
        }, 500);
    }

    /**
     *
     * @param alert
     *
     * 获取合作方列表
     */
    private void getNoticeList(String alert) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("title", titleEt.getEditableText().toString());
        params.addBodyParameter("pageNum", page + "");
        params.addBodyParameter("pageSize", Utils.ONCECOUNT + "");

        Utils.requestData(alert, this, "/notice/listData/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                NoticeListRes res = new Gson().fromJson(json, NoticeListRes.class);
                if(res.getStatus() == 1){
                    List<Notice> datas = res.getValue();
                    if(datas == null){
                        datas = new ArrayList<Notice>();
                    }
                    Message msg = handler.obtainMessage();
                    msg.what = Constants.UPDATE;
                    msg.obj = datas;
                    msg.sendToTarget();
                }else{
                    showToast(res.getMsg());
                    if (page == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json) {
                if (page == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    private void process(List<Notice> datas){
        if (page == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            noticeList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            noticeList.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        adapter.setDataList(noticeList);
    }

    @OnClick({R.id.iv_back, R.id.add})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.add:
                Intent intent = new Intent();
                intent.setClass(this, NoticeAddActivity.class);
                intent.putExtra("fromEnterprise", fromEnterprise);
                startActivityForResult(intent, 0);//0新增 1详情
                break;
        }
    }

    @Override
    public void onClick(Object o) {
        Notice notice = (Notice) o;
        if(notice == null){
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, NoticeDetailActivity.class);
        intent.putExtra("fromEnterprise", fromEnterprise);
        intent.putExtra("notice", notice);
        startActivityForResult(intent, 1);//0新增 1详情
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0 && resultCode == RESULT_OK){//0新增 1编辑 2详情
            //编辑返回
            initData();
        }else if(requestCode == 1 && resultCode == RESULT_OK){
            //详情返回
            initData();
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        initData();
    }
}
